package com.common.utils;

/**
 * 字符串操作工具类
 *
 * @author xin.ding
 * @date 2019/12/12 9:39
 */
public class StringUtils {

    /**
     * 替换字符串值中所有指定字符
     *
     * @param str        要替换字符串
     * @param searchStr  要替换的字符
     * @param replaceStr 替换后的字符
     * @return 替换后的字符串
     */
    public static String replaceAll(String str, String searchStr, String replaceStr) {
        return replaceBetweenAll(str, 0, str.length(), searchStr, replaceStr);
    }


    /**
     * 替换指定起始位置所有指定字符串值
     *
     * @param str        要替换字符串
     * @param fromIndex  替换开始索引
     * @param endIndex   替换结束索引
     * @param searchStr  要替换的字符
     * @param replaceStr 替换后的字符
     * @return 替换后的字符串
     */
    public static String replaceBetweenAll(String str, int fromIndex, int endIndex, String searchStr, String
            replaceStr) {
        if (isEmpty(str) || isEmpty(searchStr)) {
            return "";
        }
        if (isEmpty(replaceStr)) {
            replaceStr = "";
        }
        //起始、结束位置处理
        final int strLength = str.length();
        final int searchStrLength = searchStr.length();
        if (fromIndex > strLength) {
            return str;
        } else if (fromIndex < 0) {
            fromIndex = 0;
        }
        if (endIndex < fromIndex) {
            return str;
        } else if (endIndex > strLength) {
            endIndex = strLength;
        }

        final StringBuilder result = new StringBuilder();
        //拼接开始位置之前字符串
        if (0 != fromIndex) {
            result.append(str.subSequence(0, fromIndex));
        }
        String subStr = str.substring(fromIndex, endIndex);

        int preIndex = 0;
        int index;
        //循环遍历替换所有
        while ((index = subStr.indexOf(searchStr, preIndex)) > -1) {
            result.append(subStr.subSequence(preIndex, index));
            result.append(replaceStr);
            preIndex = index + searchStrLength;
        }
        //替换字符串之后字符串
        if (preIndex < subStr.length()) {
            result.append(subStr.subSequence(preIndex, subStr.length()));
        }
        //拼接结束位置之后字符串
        result.append(str.subSequence(endIndex, strLength));

        return result.toString();
    }

    /**
     * 字符串是否为空 null ""
     *
     * @param str 被检测的字符串
     * @return 是否为空
     */
    public static boolean isEmpty(CharSequence str) {
        return str == null || str.length() == 0;
    }

    /**
     * 移除最后一个搜索字符串
     *
     * @param str    原字符串
     * @param remove 要移除的字符串
     * @return
     */
    public static String removeLast(String str, String remove) {
        return org.apache.commons.lang3.StringUtils.removeEnd(str, remove);
    }
}
